require "lotteryCfg"

local _lotteryCfg = lotteryCfg

LotteryPanel = class("LotteryPanel")

local cntY = 0
local objY = 0


function LotteryPanel.create(parent)
    local panel = LotteryPanel.new()
    panel:init(parent)

    uiEffect.bounceIn(panel.view)
    panel.view:setPosition(pp.center.x, pp.center.y)
    
    parent:base_onOpenWin(panel)
    return panel
end


function LotteryPanel:init(parent)
    self.view = ccs.GUIReader:getInstance():widgetFromJsonFile("lotteryPanel.json")
    parent.widget:addChild(self.view)
    self.view:setLocalZOrder(pp.z_lottery)
    self.parent = parent

    self.roundbg = self.view:getChildByName("_bg")
    self.roundbg_r = self.roundbg:getContentSize().height/2

    local holder_cnt = self.roundbg:getChildByName("_holder_cnt")
    cntY = holder_cnt:getPositionY() - self.roundbg_r
    holder_cnt:removeFromParent(true)

    local holder_obj = self.roundbg:getChildByName("_holder_obj")
    objY = holder_obj:getPositionY() - self.roundbg_r
    holder_obj:removeFromParent(true)

    
    local function btCloseCallback(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            AudioEngine.playEffect(sound.btn2)
        elseif eventType == ccui.TouchEventType.ended then
            self.parent.lotteryPanel = nil
            uiEffect.bounceOut(self.view, true)
            self.parent:base_onCloseWin(self)
         end
    end
    self.bt_close = self.view:getChildByName("_close")
    self.bt_close:addTouchEventListener(btCloseCallback)

    --push start
    local function btPushCallback(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            AudioEngine.playEffect(sound.btn2)
        elseif eventType == ccui.TouchEventType.ended then
            self:startLottery()
         end
    end
    self.bt_push = self.view:getChildByName("_bt_push")
    self.bt_push:addTouchEventListener(btPushCallback)

    self.ui_btCost = uiUtil.createBMFontByHolder(self.bt_push, "_holder_cnt", pp.fnt_number_yellow)
    self.ui_btCost:setString("")
    self.ui_btCost:setScale(0.65)

    self.ui_btCoin = self.bt_push:getChildByName("coin")

    self.ui_startimg = self.bt_push:getChildByName("_start")

    --next time
    self.ui_bottombg = self.view:getChildByName("_bottomBg")
    self.ui_nextTime = uiUtil.createBMFontByHolder(self.ui_bottombg, "_holder_time", pp.fnt_number_white)
    self.ui_nextTime:setString("00:00")
    self.ui_nextTime:setScale(0.7)
    self.ui_bottombg:setPositionY(self.ui_bottombg:getPositionY() + 250)



    -------------------------------------
    --init objs

    local divDeg = 360/_lotteryCfg.divCnt
    for i = 1, _lotteryCfg.divCnt do
    	local deg = divDeg*(-0.5+i)
    	local sin_deg = math.sin(deg/ 180 * math.pi)
    	local cos_deg = math.cos(deg/ 180 * math.pi)

    	--cnt
    	local cnt_x = sin_deg * cntY
    	local cnt_y = cos_deg * cntY

    	local cntstr = string.format("×%d", _lotteryCfg.objInfo[i].cnt)
    	local cntfnt = cc.LabelBMFont:create(cntstr, pp.fnt_number_yellow)
        cntfnt:setPosition(self.roundbg_r+cnt_x, self.roundbg_r+cnt_y)
        cntfnt:setRotation(deg)
        cntfnt:setScale(0.45)
        self.roundbg:addChild(cntfnt)

    	--obj
    	local obj_x = sin_deg*objY
    	local obj_y = cos_deg*objY

        local obj_img = ccui.ImageView:create(_lotteryCfg.objInfo[i].gameObjRef.img, ccui.TextureResType.localType)
        obj_img:setPosition(self.roundbg_r+obj_x, self.roundbg_r+obj_y)
        obj_img:setRotation(deg)
        obj_img:setScale(0.8)
        self.roundbg:addChild(obj_img)
    end



    -------------------------------------
    self.curRot = 0
    self:refreshCost()

    if not userData:lottery_isFree() then
        self:popInBottombg()
    end

    -------------------------------------
    local function update(delta)
        self:update(delta)
    end
    self.view:scheduleUpdateWithPriorityLua(update, 0)
end

function LotteryPanel:refreshCost()
    local costCoin = _lotteryCfg.costInfo[userData.lottery_useTime].cost
    -- body

    if costCoin <= 0 or userData:lottery_isFree() then
        self.ui_btCost:setVisible(false)
        self.ui_btCoin:setVisible(false)
        self.ui_startimg:setVisible(true)
    else
        self.ui_btCost:setVisible(true)
        self.ui_btCoin:setVisible(true)
        self.ui_btCost:setString(string.format("%d", costCoin))

        self.ui_startimg:setVisible(false)
    end
end

-- 0:stop, 1:acc, 2:stable, 3:dec
local stateInfo = {
    [1] = {time = 0.7, random = 0.5, acc = 1300},
    [2] = {dec = 350},
}

function LotteryPanel:startLottery()
    --logic
    local useTime = userData.lottery_useTime
    if useTime > #_lotteryCfg.costInfo then
        useTime = #_lotteryCfg.costInfo
    end

    local canStart = false
    local cost = 0

    local bNeedPopInBottombg = false
    if userData:lottery_isFree() then
        canStart = true
        bNeedPopInBottombg = true
    else
        local costCoin = _lotteryCfg.costInfo[useTime].cost
        if userData.coin < costCoin then
            uiPopNotify:popString(gameUtil.curLuaScene.widget, "金币不足")
            if DEF_CHN_XNY then
                pchCenter:order(pchCfg.item.JinBiLiBao)
            else
                WarningPanel.create(self.parent, "Pay_level_Libao_Jinbi")
            end
        else
            if costCoin == 0 then
                bNeedPopInBottombg = true
            end
            userData.coin = userData.coin - costCoin
            canStart = true
        end
    end

    if canStart then
         -- ui
        do
            self.rotstate = 1
            self.statepassTime = 0
            self.speed = 0

            --每次转的随机值从这里得到
            self.accTime = stateInfo[1].time + math.random()*stateInfo[1].random 

            self.bt_push:setEnabled(false)
            self.bt_close:setEnabled(false)

            self.rotating = true
        end

        --logic
        do
            userData.lottery_useTime = userData.lottery_useTime + 1
            if userData.lottery_useTime > #_lotteryCfg.costInfo then
                userData.lottery_useTime = #_lotteryCfg.costInfo
            end

            self.parent:refreshCoin(userData.coin)

            userData:lottery_calcNextRestoreTime()
            gameUtil.flushUserRecord()

            ----
            -- local _levelData = require "levelData"
            -- _levelData.lottery_bFree = false
            self:refreshCost()
        end

    end

    if bNeedPopInBottombg then
        self:popInBottombg()

    end
    
end


function LotteryPanel:update( delta )
    -- body
    if self.rotating then
        self.statepassTime = self.statepassTime + delta

        if self.rotstate == 1 then
            local incrSpeed = stateInfo[1].acc * delta
            self.speed = self.speed + incrSpeed
            local average = self.speed - 0.5*incrSpeed
            local passed = average * delta
            self.curRot = self.curRot + passed
            self.roundbg:setRotation(self.curRot)

            if self.statepassTime > self.accTime then
                self.rotstate = 2
                self.statepassTime = 0
            end

        elseif self.rotstate == 2 then
            local decSpeed = stateInfo[2].dec * delta
            self.speed = self.speed - decSpeed
            if self.speed < 0 then
                self.rotstate = 0
                self.statepassTime = 0
                -- self.view:unscheduleUpdate()
                self.bt_push:setEnabled(true)
                self.bt_close:setEnabled(true)

                self.rotating = false

                self:getAward()
            else
                local average = self.speed + decSpeed*0.5
                local passed = average * delta
                self.curRot = self.curRot + passed
                self.roundbg:setRotation(self.curRot)
            end
            
        else --0
            
        end
    end
    

    --refresh left time
    if self.parent.lotteryRestoreNeedTime then
        self.ui_nextTime:setString(self.parent.lotteryRestoreNeedTime)
    end

end

function LotteryPanel:getAward()
    -- body
    local rot = math.abs(self.curRot) % 360
    rot = 360 - rot

    local award
    local rotitv = 360/_lotteryCfg.divCnt
    for i = 1, _lotteryCfg.divCnt do
        if rot >= (i-1)*rotitv and rot < i*rotitv then
            award = _lotteryCfg.objInfo[i]
            break
        end
    end

    gameUtil.gettingAward({award})
    self.parent:refreshCoin(userData.coin)
    AudioEngine.playEffect(sound.fuhuo)
end


function LotteryPanel:onTimeRestored()
    -- body
    self:refreshCost()

    self:popOutBottombg()
end

function LotteryPanel:popInBottombg(d)
    local delay = d or 0
    local function inAction()
            local ui = self.ui_bottombg
            uiEffect.MoveIn(ui, 
                cc.p(0,  -100),
                cc.p(0,  -200)
                )
        end

    self.ui_bottombg:stopAllActions()
    self.ui_bottombg:runAction(cc.Sequence:create(
        cc.DelayTime:create(delay),
        cc.CallFunc:create(inAction)
        ))

end 

function LotteryPanel:popOutBottombg(d)
    local delay = d or 0
    local function inAction()
            local ui = self.ui_bottombg
            uiEffect.MoveOut(ui, 
                cc.p(0, -200),
                cc.p(0, -100)
                )
        end
    self.ui_bottombg:stopAllActions()
    self.ui_bottombg:runAction(cc.Sequence:create(
        cc.DelayTime:create(delay),
        cc.CallFunc:create(inAction)
        ))

end











